#!/usr/bin/env coffee

import { parse } from '@fast-csv/parse'
import {join} from 'path'
import fs from 'fs'

DAY = 86400*1000

int2day = (day, base=DAY)=>
  new Date(day*base).toISOString()[..9]

_parse = (fp)=>
  user_create = new Map()
  day_user = new Map()

  base = DAY*7
  stream = parse({ headers: true })
  .on('error', (error) => console.error(error))
  .on(
    'data'
    ({u,t}) =>
      d = parseInt new Date(...t.split("-").map((i)=>parseInt(i)))/base
      pd = user_create.get(u)
      if (pd==undefined) or pd > d
        user_create.set(u, d)

      m = day_user.get(d)
      if not m
        m = new Set()
        day_user.set(d, m)
      m.add(u)

  ).on(
    'end'
    =>
      day = new Set()

      for d from user_create.values()
        day.add(d)

      day = [...day]
      day.sort()

      li = ['user','']
      r = [li]
      for i from day
        d = int2day(i, base)
        li.push d
        t = ['',d]
        r.push t
        iu = [...day_user.get(i)]
        for j from day
          if j >= i
            ju = day_user.get(j)
            n = iu.filter((x)=>ju.has(x)).length
            if j == i
              t[0] = n
              t.push ''
            else
              t.push Math.round(10000*n/t[0])/100
          else
            t.push ''

      txt = []
      for i in r
        txt.push i.join(',')
      fs.writeFileSync(fp[..-4]+"out.csv", txt.join('\n'))
  )

  fs.createReadStream(fp).pipe stream


do =>
  dir = "/Users/z/git/t/src"
  for i in [0..2]
    fp = join dir, "user_activity-role#{i}.csv"
    _parse fp
    console.log fp
